package ua.com.alus.resvac.crm.services.spring.security;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import ua.com.alus.resvac.crm.domen.entities.Account;
import ua.com.alus.resvac.crm.services.spring.AccountService;

import java.util.Arrays;

/**
 * UserDetailsService implementation
 */
public class CrmUserDetailsService implements UserDetailsService {

    private AccountService accountService;

    public AccountService getAccountService() {
        return accountService;
    }

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        Account account = getAccountService().getAccount(username);
        if (account != null) {
            GrantedAuthority grantedAuthority;
            switch (account.getAccountType()) {
                case ROLE_RESUME:
                    grantedAuthority = SecurityUtils.RESUME;
                    break;
                case ROLE_VACANCY:
                    grantedAuthority = SecurityUtils.VACANCY;
                    break;
                default:
                    grantedAuthority = SecurityUtils.ROLE_USER_AUTH;
            }
            return new User(account.getUserName(), account.getPassword(), true, true, true, true,
                    Arrays.asList(grantedAuthority));
        }
        return null;
    }
}
